# #!/usr/bin/env python
# # -*- coding:utf-8 -*-
# """
# @File   : test11_ddns.py
# @Time : 2025/2/28 14:17
# @Author: Wangwc
# @Describe:  ……
# """
# import datetime
# import random
# import time
# import warnings
#
# warnings.filterwarnings("ignore", category=DeprecationWarning)
# from urllib3.exceptions import InsecureRequestWarning
#
# warnings.simplefilter('ignore', category=InsecureRequestWarning)
# import allure
# import pytest
#
# from utils.ddns_tools import PostgresSSHOperator as ddns
# from business.SystemApi import SystemApi
# from utils.login import Login
# from commons.logger import log
# from utils.config_tools import Config
#
# # TODO 当前模块的配置文件名称，配置在config目录下
# config_name = "user.ini"
# login = Login(config_name=config_name)
# config = Config(config_name=config_name)
#
# global_token = None
#
# @pytest.fixture(scope="function")
# def system_api():
#     global global_token
#     if global_token is None:
#         global_token = login.login()
#     api = SystemApi(global_token, configname=config_name)
#     return api
#
#
# def handle_api_call(api_method, *args, attach_to_allure=True, format_result=None,**kwargs):
#     if not callable(api_method):
#         raise TypeError("api_method 参数必须是可调用对象（如函数或方法）")
#     if attach_to_allure is not None and not isinstance(attach_to_allure, bool):
#         raise TypeError("attach_to_allure 参数必须是布尔类型或者为 None")
#     if format_result is not None and not callable(format_result):
#         raise TypeError("format_result 参数必须是可调用对象（如函数）或者为 None")
#
#     max_retries = 3
#     for retry in range(max_retries):
#         try:
#             result = api_method(*args,**kwargs)
#             # 检查响应是否为字典类型
#             if isinstance(result, dict):
#                 # 判断 token 是否失效
#                 if result.get('code') == 1024 and 'Login has expired' in result.get('msg', ''):
#                     if retry < max_retries - 1:
#                         allure.attach(str(result), f"{api_method.__name__} 调用结果：token 失效，尝试重新登录", allure.attachment_type.TEXT)
#                         log.info(f"{api_method.__name__} 调用结果：token 失效，尝试重新登录")
#                         global global_token
#                         global_token = login.login()
#                         api_method.__self__.token = global_token
#                         continue
#                     else:
#                         allure.attach(str(result), f"{api_method.__name__} 调用结果：token 失效，重试次数已用完", allure.attachment_type.TEXT)
#                         log.error(f"{api_method.__name__} 调用结果：token 失效，重试次数已用完")
#                         raise Exception("token 失效，重试次数已用完")
#             if attach_to_allure:
#                 if format_result:
#                     formatted_result = format_result(result)
#                 else:
#                     formatted_result = str(result)
#                 allure.attach(formatted_result, f"{api_method.__name__} 调用结果", allure.attachment_type.TEXT)
#             log.info(f"{api_method.__name__} 调用成功")
#             return result
#         except Exception as e:
#             allure.attach(str(e), f"{api_method.__name__} 调用错误信息", allure.attachment_type.TEXT)
#             log.error(f"{api_method.__name__} 调用出现错误: {e}", exc_info=True)
#             if isinstance(e, ConnectionError):
#                 log.error("连接错误，可能是网络问题，请检查网络连接。")
#             elif isinstance(e, ValueError):
#                 log.error("值错误，可能是传入的参数有误，请检查参数。")
#             raise
#
#
# @allure.feature("控制面板-DDNS稳定性")
# class TestSystemManagement():
#     @allure.title("DDNS稳定性")
#     @pytest.mark.parametrize("execution_number", range(100))
#     def test_ddns(self, system_api, execution_number):
#         allure.dynamic.title(f"DDNS稳定性 - 第 {execution_number + 1} 次执行")
#
#         with allure.step(f"第 {execution_number + 1} 次检查DDNS是否为空"):
#             time.sleep(20)
#             log.info(f"第{execution_number + 1}次次检查DDNS是否为空")
#             result_list = handle_api_call(system_api.get_ddns_list)
#             if result_list:
#                 ids = [item.get('id') for item in result_list]
#                 for id in ids:
#                     handle_api_call(system_api.delete_ddns, id)
#                     time.sleep(1)
#             new_result_list = handle_api_call(system_api.get_ddns_list)
#             log.info(f"清理之后的DDNS列表信息为：{new_result_list}")
#
#         with allure.step(f"第 {execution_number + 1} 次执行：加入阿里云DDNS"):
#             log.info(f"第{execution_number + 1}次执行：加入阿里云DDNS")
#             server1 = config.read_config_ini('ddns', 'server1')
#             domain1 = config.read_config_ini('ddns', 'domain1')
#             accessID1 = config.read_config_ini('ddns', 'accessID1')
#             Accesskey1 = config.read_config_ini('ddns', 'Accesskey1')
#             try:
#                 handle_api_call(system_api.add_ddns, server1, domain1, accessID1, Accesskey1)
#             except Exception as e:
#                 log.warning(f"添加阿里云DDNS时出现异常，但将继续检查SSH验证: {str(e)}")
#                 allure.attach(str(e), "添加阿里云DDNS异常，但继续执行后续检查", allure.attachment_type.TEXT)
#             time.sleep(1)
#
#         with allure.step(f"第 {execution_number + 1} 次执行：确认成功加入阿里云DDNS"):
#             log.info(f"第{execution_number + 1}次执行：确认成功加入阿里云DDNS")
#             host = '172.17.20.123'
#             ssh_username = 'root'
#             ssh_password = 'Aa123456@'
#             ddns_client = ddns(host, ssh_username, ssh_password)
#             results = ddns_client.get_ddns_data()
#             assert results[0].get('service_provider') == server1
#             assert results[0].get('domain') == domain1
#             assert results[0].get('access_id') == accessID1
#             assert results[0].get('access_key') == Accesskey1
#
#         with allure.step(f"第 {execution_number + 1} 次执行：编辑DDNS信息为腾讯云"):
#             log.info(f"第{execution_number + 1}次执行：编辑DDNS信息为腾讯云")
#             ddns_id = handle_api_call(system_api.get_ddns_list)[0].get('id')
#             server2 = config.read_config_ini('ddns', 'server2')
#             domain2 = config.read_config_ini('ddns', 'domain2')
#             accessID2 = config.read_config_ini('ddns', 'accessID2')
#             Accesskey2 = config.read_config_ini('ddns', 'Accesskey2')
#             handle_api_call(system_api.edit_ddns, ddns_id, server2, domain2, accessID2, Accesskey2)
#             time.sleep(1)
#
#         with allure.step(f"第 {execution_number + 1} 次执行：确认成功修改为腾讯DDNS"):
#             log.info(f"第{execution_number + 1}次执行：确认成功修改为腾讯DDNS")
#             new_results = ddns_client.get_ddns_data()
#             assert new_results[0].get('service_provider') == server2
#             assert new_results[0].get('domain') == domain2
#             assert new_results[0].get('access_id') == accessID2
#             assert new_results[0].get('access_key') == Accesskey2
#
#         with allure.step(f"第 {execution_number + 1} 次执行：删除DDNS"):
#             log.info(f"第{execution_number + 1}次执行：删除DDNS")
#             handle_api_call(system_api.delete_ddns, ddns_id)
#             time.sleep(1)
#
#         with allure.step(f"第 {execution_number + 1} 次执行：确认删除成功"):
#             log.info(f"第{execution_number + 1}次执行：确认删除成功")
#             final_results = ddns_client.get_ddns_data()
#             assert len(final_results) == 0